App = {
  web3Provider: null,
  contracts: {},

  shopcarArray: [],  //购物车数组

  init: async function () {
    // Load shopmal.
    return await App.initWeb3();
  },

  initWeb3: async function () {
    // Modern dapp browsers...
    if (window.ethereum) {
      console.log('1')
      App.web3Provider = window.ethereum;
      try {
        // Request account access
        await window.ethereum.enable();
      } catch (error) {
        // User denied account access...
        console.error("User denied account access")
      }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
      console.log('2')
      App.web3Provider = window.web3.currentProvider;
    }
    // If no injected web3 instance is detected, fall back to Ganache
    else {
      console.log('3')
      App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:8545');
    }
    web3 = new Web3(App.web3Provider);

    return App.initContract();
  },

  initContract: function () {
    // 加载Adoption.json，保存了Adoption的ABI（接口说明）信息及部署后的网络(地址)信息，它在编译合约的时候生成ABI，在部署的时候追加网络信息
    $.getJSON('Adoption.json', function (data) {
      // 用Adoption.json数据创建一个可交互的TruffleContract合约实例。
      App.contracts.Adoption = TruffleContract(data);

      // Set the provider for our contract
      App.contracts.Adoption.setProvider(App.web3Provider);

      App.contracts.Adoption.deployed().then(function(instance){
        App.adoptionInstance = instance;
        return App.getOrders();
      })
      // Use our contract to retrieve and mark the adopted pets
     
    });
    return App.bindEvents();
  },

  bindEvents: function () {
    $(document).on('click', '.btn-adopt', App.addshop);
    $(document).on('click', '.back', App.jump);
    $(document).on('click', '.choose', App.select);
    $(document).on('click', '.pay', App.pay);
  },

  getOrders: function () {
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      // 发送交易获取购物车
      App.adoptionInstance.getOrder(account).then(function(orders){
        var petsRow = $('#shopmal');
        var petTemplate = $('#shopTemplate');

        $.getJSON('../pets.json', function (data) {
          for (i = 0; i < orders.length; i++) {
            if(orders[i]!= 0){
              let amount = '×'+ orders[i]
              let sum = data[i].price * orders[i]
              let orderid = '98670000235' + i
              petTemplate.find('.name').text(data[i].name);
              petTemplate.find('.img').attr('src', data[i].picture);
              petTemplate.find('.amount').text(amount);
              petTemplate.find('.sum').text(sum);
              petTemplate.find('.orderid').text(orderid);
             
              petsRow.append(petTemplate.html());
            }
           
          };        
        })
      }).catch(function(err){
        console.log('getshopcarlen',err)
      })
     
    });
  },

  getShopcar: function () {
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      // 发送交易获取购物车
      App.adoptionInstance.getShopcars(account).then(function(shopcars){
        $.getJSON('../pets.json', function (data) {
          for (i = 0; i < shopcars.length; i++) {
            if(shopcars[i]!= 0){
              let amount = '×'+ shopcars[i]  
              let id = '#' + i  
              $(id).text(amount);          
            }
           
          };        
        })
      }).catch(function(err){
        console.log('getshopcarlen',err)
      })
     
    });
  },

  addshop: function (event) {
    event.preventDefault();
    var shopId = parseInt($(event.target).data('id'));
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log('addshop',error);
      }
      var account = accounts[0];
      App.adoptionInstance.addshop(shopId, { from: account }).then(function(){
        return App.getShopcar();
      }).catch(function (err) {
        console.log('addshoperr',err.message);
      });
    });
  },

  select: function (event) {
    event.preventDefault();
    if($(event.target).children("img").length == 1){  //img displaynone,点击的是div
      $(event.target).removeClass('unselect')
      $(event.target).addClass('select')
      $(event.target).children("img").css("display","block")
      //$(event.target).append('<img style="width:24px;height:24px;" src="images/selected.png">')     
    }
    else {     //点击的是img
      $(event.target).css("display","none")
      $(event.target).parent().removeClass('select')
      $(event.target).parent().addClass('unselect')
    }
   
    //parseInt($(event.target).data('id'));
  },

  pay: function() {
    let arr = []
    $('.choose').each(function(){
      if($(this).hasClass("select") == true){
        let id = $(this).data('id');
        let idch = '#' + id ; 
        let amount = parseInt($(idch).text().substring(1,2)); 
        let elem = {
          id:id,
          amount:amount
        } 
        arr.push(elem)
      }
    });
    let url = `pay.html?tt=${JSON.stringify(arr)}`
    window.location.href=encodeURI(url);
  },

  jump: function() {
    window.location.href="my.html"; 
  }

};

$(function () {
  $(window).on('load',function () {
    App.init();
  });
});

